package cn.edu.zime.tjh.client;

import cn.edu.zime.tjh.handler.EchoUDPClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.util.CharsetUtil;

import java.net.InetSocketAddress;
import java.util.Scanner;

public class EchoUDPClient {
    private static final String HOST = "127.0.0.1";

    private static final int PORT = 9000;

    public EchoUDPClient(){

    }

    public void start(){
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioDatagramChannel.class)
                    .option(ChannelOption.SO_BROADCAST, true)
                    .handler(new ChannelInitializer<NioDatagramChannel>() {
                        @Override
                        protected void initChannel(NioDatagramChannel ch) {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new EchoUDPClientHandler());
                        }
                    });

            // 绑定随机端口（UDP客户端不需要指定端口）
            Channel channel = b.bind(0).sync().channel();
            System.out.println("UDP client started, enter messages to send to server (type 'exit' to quit)");

            InetSocketAddress serverAddress = new InetSocketAddress(HOST, PORT);
            Scanner scanner = new Scanner(System.in);

            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                if ("exit".equalsIgnoreCase(line)) {
                    break;
                }

                // 创建UDP数据包
                ByteBuf buf = channel.alloc().buffer();
                buf.writeCharSequence(line, CharsetUtil.UTF_8);
                DatagramPacket packet = new DatagramPacket(buf, serverAddress);

                // 发送消息
                channel.writeAndFlush(packet);
                System.out.println("Sent: " + line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            group.shutdownGracefully();
        }
    }
}
